
import axios from 'axios'
import { errorDeal, getStore, globalLoading, successDeal } from '@/utils/utils'
import JsBridge from '@/utils/JsBridge.js'
import { showLoadingToast, closeToast, showToast } from 'vant';
import store from '@/store'

axios.interceptors.request.use(function (config) {
  return config;
}, function (error) {

  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});


const isApp = store.state.isApp

/**
 * 
 * 获取鉴权信息
 */
export const getAuth = () => {
  return new Promise((resolve, reject) => {
    let userInfo = getStore('USER_INFO_MF')

    if (!userInfo) {
      resolve(false)
    } else {
      if (isApp) {
        let json = {
          "timestamp": new Date().getTime(),
          "tmsi": userInfo.tmsi,
          "userId": userInfo.userId,
        }
        JsBridge.callHandler('createAuthorization', json, (response) => {
          let res = ""
          try {
            res = JSON.parse(response)
            resolve(res)
          } catch (err) {
            showToast(err.message)
          }
        })
      } else {
        resolve({
          header: {
            userId: userInfo.userId,
            Authorization: `${userInfo.userId},'',${getExplorerInfo()},3,20,''`,
            platformHeadType: 'rcmsPlatform'
          },
          body: {
            token: 'Bearer ' + userInfo.token,
            userId: userInfo.userId,
          }
        })
      }
    }
  })
}

const getExplorerInfo = function () {
  var explorer = window.navigator.userAgent.toLowerCase()
  //ie
  if (explorer.indexOf('msie') >= 0) {
    var ver = explorer.match(/msie ([\d.]+)/)[1]
    return `IE${ver}`
  }
  //firefox
  else if (explorer.indexOf('firefox') >= 0) {
    var ver = explorer.match(/firefox\/([\d.]+)/)[1]
    return `Firefox${ver}`
  }
  //Chrome
  else if (explorer.indexOf('chrome') >= 0) {
    var ver = explorer.match(/chrome\/([\d.]+)/)[1]
    return `Chrome${ver}`
  }
  //Opera
  else if (explorer.indexOf('opera') >= 0) {
    var ver = explorer.match(/opera.([\d.]+)/)[1]
    return `Opera${ver}`
  }
  //Safari
  else if (explorer.indexOf('Safari') >= 0) {
    var ver = explorer.match(/version\/([\d.]+)/)[1]
    return `Safari${ver}`
  }
}

/**
 *@describe http请求
 *@method {String} 请求方式
 *@url {String} 接口地址
 *@params {Object} 对应接口参数
 **/
export default async function _http(method = 'post', { url, apiName = '' }, params = {}, loading = true, headers = {}) {
  if (loading) {
    showLoadingToast({
      message: '请求中...',
      forbidClick: true,
      duration: 0,
    });
  }

  const boryaAuth = await getAuth()
  const Authorization = { Authorization: boryaAuth ? boryaAuth.header.Authorization : '' }

  let json = {
    Token: boryaAuth ? boryaAuth.body.token : '',
    platformHeadType: boryaAuth ? boryaAuth.header.platformHeadType : ''
  }

  return axios({
    method: method,
    url: '' + url,

    headers: Object.assign({
      'Content-Type': params.contentType ? 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq' : 'application/json;charset=UTF-8;'
    }, json, boryaAuth ? Authorization : '', headers),
    params: method === 'get' ? params : '' || method === 'delete' ? params : '',
    data: Object.assign(params, boryaAuth.body),
    timeout: 1000 * 6,
    responseType: params.responseType == 'blob' ? 'blob' : undefined,
    withCredentials: true
  }).then(res => {
    if (loading) {
      closeToast()
    }
    // 数据流，直接返回
    if (params.responseType == 'blob') {
      return res
    }

    if (res && res.data && res.data.code == 200) {
      return res.data
    } else throw res.data
  }).catch(error => {
    if (loading) {
      closeToast()
    }
    errorDeal(error)
    throw error
  })
}
